//
//  CarLogOutViewController.m
//  Rail
//
//  Created by hychen on 2018/3/17.
//  Copyright © 2018年 Hychen. All rights reserved.
//

#import "CarLogOutViewController.h"
#import "LineDetailDescTableViewCell.h"
#import "ButtonTableViewCell.h"
#import "NSDate+Category_lib.h"

#import "BMUsefulPickerView.h"

#import "SelectPhotoTableViewCell.h"

@interface CarLogOutViewController ()
@property (nonatomic, strong) NSDate *logoutTime;
@property (nonatomic, strong) NSMutableArray *selectPhotoArray;
//进岗时间
@property (nonatomic, strong) NSDate *inDate;
//离岗年月日
@property (nonatomic, copy) NSString *outDateString;
//离岗时分
@property (nonatomic, copy) NSString *outTimeString;
@property (nonatomic, assign) BOOL isUploading;
@end

@implementation CarLogOutViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.navigationItem addSimpleTitleView:@"车辆离岗"];
    
    NSDateFormatter *fmt = [NSDateFormatter new];
    fmt.dateFormat = @"yyyy-MM-dd HH:mm:ss.S";
    if ([self.model.in_time objectIsNotEmpty] && self.model.in_time.length > 18) {
        self.inDate = [fmt dateFromString:self.model.in_time];
    }
    
    self.logoutTime = [NSDate date];
    [self setupTableViewData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)setupTableViewData {
    if (!self.outDateString) {
        NSString *logoutDate = [self.logoutTime formatYearMonthDay_lib];
        self.outDateString = logoutDate;
    }

    if (!self.outTimeString) {
        NSString *logoutHour = [NSString stringWithFormat:@"%02ld:%02ld",self.logoutTime.hour,self.logoutTime.minute];
        self.outTimeString = logoutHour;
    }

    self.dataArray = @[
                       @{@"title":@"车牌号码",@"data":self.model.plate_num?:@""},
                       @{@"title":@"离岗日期",@"data":self.outDateString?:@""},
                       @{@"title":@"离岗时间",@"data":self.outTimeString?:@""},
                       @{@"title":@"离岗照片",@"data":@""},
                       @{@"title":@"保存",@"data":@""},
                       ].mutableCopy;
    
    [self.tableView reloadData];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 5;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row <= 2) {
        NSDictionary *dict = [self.dataArray objectAtIndex:indexPath.row];
        LineDetailDescTableViewCell *cell = [LineDetailDescTableViewCell cellWithTableView:tableView class:[LineDetailDescTableViewCell class]];
        cell.titleLabel.text = [dict objectForKey:@"title"];
        cell.contentLabel.text = [dict objectForKey:@"data"];
        cell.showArrow = indexPath.row != 0;
        return cell;
    }
    if (indexPath.row == 3) {
        SelectPhotoTableViewCell *cell = [SelectPhotoTableViewCell cellWithInitStyleTableView:tableView class:[SelectPhotoTableViewCell class]];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        [cell setTitle:@"离岗照片"];
        [cell setPhotoArray:self.selectPhotoArray];
        BMWeakSelf
        [cell setBlockSelectPhotoArray:^(NSArray *photoArray) {
            weakSelf.selectPhotoArray = [NSMutableArray arrayWithArray:photoArray];
        }];
        return cell;
    }
    if (indexPath.row == 4) {
        ButtonTableViewCell *cell = [ButtonTableViewCell cellWithTableView:tableView class:[ButtonTableViewCell class]];
        NSDictionary *dict = [self.dataArray objectAtIndex:indexPath.row];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.buttonTitle = [dict objectForKey:@"title"];
        BMWeakSelf
        [cell setBlockClickEventButton:^{
            [weakSelf requestCarLogOut];
        }];
        
        return cell;
    }
    return [UITableViewCell new];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row <= 2) {
        return 50.f;
    }
    if (indexPath.row == 3) {
        return 160.f;
    }
    if (indexPath.row == 4) {
        return 200.f;
    }
    return 0;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    BMWeakSelf
    if (indexPath.row == 1) {
        BMDatePickerViewStyle *style = [BMDatePickerViewStyle new];
        style.date = [NSDate date];
        if ([self.inDate isKindOfClass:[NSDate class]]) {
            style.minimumDate = self.inDate;
        }
        style.maximumDate = style.date;
        style.datePickerMode = UIDatePickerModeDate;
        [BMUsefulPickerView showDatePickerWithToolBarText:@"离岗日期" withStyle:style toolBarStyle:BMPickerViewToolBarStyleText cancelBlock:^{
            
        } clickBlock:^(NSDate *selectedDate) {
            weakSelf.outDateString = [selectedDate formatYearMonthDay_lib];
            [weakSelf setupTableViewData];
        } valueChangeBlock:^(NSDate *selectedDate) {
            
        }];
    }
    else if (indexPath.row == 2) {
        BMDatePickerViewStyle *style = [BMDatePickerViewStyle new];
        style.date = [NSDate date];
        if ([self.inDate isKindOfClass:[NSDate class]]) {
            style.minimumDate = self.inDate;
        }
        style.datePickerMode = UIDatePickerModeTime;
        [BMUsefulPickerView showDatePickerWithToolBarText:@"离岗时间" withStyle:style toolBarStyle:BMPickerViewToolBarStyleText cancelBlock:^{
            
        } clickBlock:^(NSDate *selectedDate) {
            weakSelf.outTimeString = [selectedDate formatMinuteSecond_lib];
            [weakSelf setupTableViewData];
        } valueChangeBlock:^(NSDate *selectedDate) {
            
        }];
    }
}

- (void)requestCarLogOut {
    
    if (self.isUploading) {
        return;
    }
    
    BMWeakSelf
    if (![BMUtils checkOpen4gAutoUploadWithCompletion:^{
        [weakSelf _requestCarLogOut];
    }]) {
        return;
    }
    
    [self _requestCarLogOut];
}

- (void)_requestCarLogOut {
    BMWeakSelf
    self.isUploading = YES;
    NSString *outString = [NSString stringWithFormat:@"%@ %@",self.outDateString,self.outTimeString];
    UIImage *image1 = nil;
    if (self.selectPhotoArray.count > 0) {
        SelectPhotoModel *imageModel = [self.selectPhotoArray objectAtIndex:0];
        image1 = [imageModel uploadImage]?:[imageModel image];
    }
    
    UIImage *image2 = nil;
    if (self.selectPhotoArray.count > 1) {
        SelectPhotoModel *imageModel = [self.selectPhotoArray objectAtIndex:1];
        image2 = [imageModel uploadImage]?:[imageModel image];
    }
    
    Show_Msg(@"离岗中")
    
    [HttpRequest requestCarLogoutWithRecordId:self.model.recordid?:@"" outTime:outString outImage1:image1 outImage2:image2 success:^(id object) {
        if (weakSelf.BlockLogoutCarSuccess) {
            weakSelf.BlockLogoutCarSuccess();
        }
        weakSelf.isUploading = NO;
        [[NSNotificationCenter defaultCenter] postNotificationName:Notify_Car_LogOut_Success object:nil];
        Show_Msg_Success(@"离岗成功")
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            NSMutableArray *array = [NSMutableArray arrayWithArray:weakSelf.navigationController.viewControllers];
            [array removeObjectAtIndex:array.count-2];
            weakSelf.navigationController.viewControllers = array.copy;
            [weakSelf.navigationController popViewControllerAnimated:YES];
            Dismiss_NoMsg
        });
    } failure:^(NSString *code, NSString *msg) {
        weakSelf.isUploading = NO;
        Show_Msg_Error(msg)
    }];
}

- (NSMutableArray *)selectPhotoArray {
    if (!_selectPhotoArray) {
        _selectPhotoArray = [NSMutableArray array];
    }
    return _selectPhotoArray;
}

@end
